<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">



  <meta name="description" content="Ajax与Flask传值的跨域问题"/>




  <meta name="keywords" content="开发, flask, ajax, 八一" />



  <meta name="baidu-site-verification" content="HhUstaSjr0" />



  <meta name="google-site-verification" content="UA-102975942-1" />






  <link rel="alternate" href="/atom.xml" title="八一">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=2.6.0" />



<link rel="canonical" href="https://bay1.top/2018/01/31/Ajax与Flask传值的跨域问题/"/>


<link rel="stylesheet" type="text/css" href="/css/style.css?v=2.6.0" />
<link rel="stylesheet" type="text/css" href="/css/prettify.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/css/sons-of-obsidian.css" media="screen" />



  <link rel="stylesheet" type="text/css" href="/lib/fancybox/jquery.fancybox.css" />




  
  <script id="baidu_analytics">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9a885cc9fb6cd7bcef579deb8efe8a70";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <script id="google_analytics">
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-102975942-1', 'auto');
        ga('send', 'pageview');
  </script>










    <title> Ajax与Flask传值的跨域问题 - 八一 </title>
  </head>

  <body><div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/." class="logo">八一</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>

<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    
      <a href="/archives">
        <li class="mobile-menu-item">
          
          
            文章
          
        </li>
      </a>
    
      <a href="/tags">
        <li class="mobile-menu-item">
          
          
            标签
          
        </li>
      </a>
    
      <a href="/about">
        <li class="mobile-menu-item">
          
          
            关于/友链
          
        </li>
      </a>
    
      <a href="/search">
        <li class="mobile-menu-item">
          
          
            站内搜索
          
        </li>
      </a>
    
  </ul>
</nav>

    <div class="container" id="mobile-panel">
      <header id="header" class="header"><div class="logo-wrapper">
  <a href="/." class="logo">八一</a>
</div>

<nav class="site-navbar">
  
    <ul id="menu" class="menu">
      
        <li class="menu-item">
          <a class="menu-item-link" href="/archives">
            
            
              文章
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/tags">
            
            
              标签
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/about">
            
            
              关于/友链
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/search">
            
            
              站内搜索
            
          </a>
        </li>
      
    </ul>
  
</nav>

      </header>

      <main id="main" class="main">
        <div class="content-wrapper">
          <div id="content" class="content">
            
  
  <article class="post">
    <header class="post-header">
      <h1 class="post-title">
        
          Ajax与Flask传值的跨域问题
        
      </h1>

      <div class="post-meta">
        <span class="post-time">
          2018-01-31
        </span>
        
        
        
      </div>
    </header>

    
    

    <div class="post-content">
      
        <p>前后端分离时,关于前端Ajax-Post数据时,遇到的一个问题<br><a id="more"></a></p>
<blockquote>
<p>在写一个报名提交的页面,前端组写了前端页面<br>但是没有写后端的传值,本来想构建Flask结构目录<br>但是想实现API的形式,可以控制提交时间段-在不招新的时间关闭后端<br>就打算分离开,form表单提交的Post一开始是这样写的</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"form"</span>).submit(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">var</span> flagname  = isname();</span><br><span class="line">	<span class="keyword">var</span> flagphone = isphone();</span><br><span class="line">	<span class="keyword">var</span> flagclass = isclass();</span><br><span class="line">	<span class="keyword">var</span> flagemail = isemail();</span><br><span class="line">	<span class="keyword">var</span> flaggroup = isgroup();</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span>(flagname == <span class="literal">true</span> &amp;&amp; flagphone == <span class="literal">true</span> &amp;&amp; flagclass == <span class="literal">true</span> </span><br><span class="line">		&amp;&amp; flagemail == <span class="literal">true</span> &amp;&amp; flaggroup == <span class="literal">true</span>)&#123;</span><br><span class="line">		<span class="keyword">var</span> data=&#123;</span><br><span class="line">			InfoNmae:InfoName.value,</span><br><span class="line">			InfoPho:InfoPho.value,</span><br><span class="line">			InfoCls:InfoCls.value,</span><br><span class="line">			InfoEmail:InfoEmail.value,</span><br><span class="line">			InfoGroup:arr,</span><br><span class="line">			InfoPower:InfoPower.value</span><br><span class="line">		&#125;;</span><br><span class="line">		$.ajax(&#123;</span><br><span class="line">			type:<span class="string">'POST'</span>,</span><br><span class="line">			url: <span class="string">"/joinus"</span>,</span><br><span class="line">			data: <span class="built_in">JSON</span>.stringify(data),</span><br><span class="line">			dataType : <span class="string">'json'</span>,</span><br><span class="line">			success:<span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</span><br><span class="line">				alert(<span class="string">"提交成功"</span>);</span><br><span class="line">			&#125;,</span><br><span class="line">			error: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>)</span>&#123;</span><br><span class="line">				<span class="keyword">var</span> json_data=<span class="built_in">JSON</span>.stringify(res);</span><br><span class="line">				alert(json_data);</span><br><span class="line">				<span class="comment">// alert("现在不迎新哦~");</span></span><br><span class="line">			&#125;,</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>后端是这样</p>
</blockquote>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@app</span>.route(<span class="string">"/joinus"</span>,methods=[<span class="string">'POST'</span>])</span><br><span class="line">def index():</span><br><span class="line">    <span class="keyword">data</span>=request.get_json(force=True)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">data</span>:</span><br><span class="line">        print(<span class="keyword">data</span>)</span><br><span class="line">        <span class="keyword">return</span> jsonify(&#123;<span class="string">"status"</span>:True&#125;)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> jsonify(&#123;<span class="string">"status"</span>:False&#125;)</span><br></pre></td></tr></table></figure>
<p>一开始想的是,直接将url改为后端运行的绝对路径不行了<br>但是修改之后发现,但是一直报500错误,后来才知道是跨域问题……</p>
<blockquote>
<p>在网上找到了<a href="http://blog.csdn.net/a1241314660/article/details/77995654" target="_blank" rel="noopener">这种方法</a><br>第一种直接修改数据类型为jsonp,采用GET方法,确实可行…..</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(&#123;</span><br><span class="line">	type:<span class="string">'POST'</span>,</span><br><span class="line">	url: <span class="string">"http://127.0.0.1:5000/joinus"</span>,</span><br><span class="line">	data: <span class="built_in">JSON</span>.stringify(data),</span><br><span class="line">	dataType : <span class="string">'jsonp'</span>,</span><br><span class="line">	success:<span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</span><br><span class="line">		alert(<span class="string">"提交成功"</span>);</span><br><span class="line">	&#125;,</span><br><span class="line">	error: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>)</span>&#123;</span><br><span class="line">		<span class="keyword">var</span> json_data=<span class="built_in">JSON</span>.stringify(res);</span><br><span class="line">		alert(json_data);</span><br><span class="line">		<span class="comment">// alert("现在不迎新哦~");</span></span><br><span class="line">	&#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>第二种就是在flask端加上响应头<br>但是上个链接中在用make_reponse()函数形成响应头时没有将数据json化<br>还是报500错误</p>
</blockquote>
<figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@app.route(<span class="string">"/api"</span>,methods=[<span class="string">'POST'</span>])</span><br><span class="line">def <span class="built_in">index</span>():</span><br><span class="line">    data=request.get_json(force=True)</span><br><span class="line">    <span class="keyword">if</span> dat<span class="variable">a:</span></span><br><span class="line">        <span class="keyword">print</span>(data)</span><br><span class="line">        <span class="keyword">res</span> = make_response(jsonify(data))</span><br><span class="line">        <span class="keyword">res</span>.headers[<span class="string">'Access-Control-Allow-Origin'</span>] = <span class="string">'*'</span></span><br><span class="line">        <span class="keyword">res</span>.headers[<span class="string">'Access-Control-Allow-Methods'</span>] = <span class="string">'POST'</span></span><br><span class="line">        <span class="keyword">res</span>.headers[<span class="string">'Access-Control-Allow-Headers'</span>] = <span class="string">'x-requested-with,content-type'</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">res</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> jsonify(&#123;<span class="string">"error"</span>:False&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>第三种是应用了flask集成的轮子<br>直接pip install flask_cors</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> flask_cors <span class="keyword">import</span> CORS</span><br><span class="line"></span><br><span class="line"><span class="comment"># r'/*' 是通配符，让本服务器所有的 URL 都允许跨域请求</span></span><br><span class="line">CORS(app, resources=<span class="string">r'/*'</span>)</span><br><span class="line"></span><br><span class="line"><span class="meta">@app.route("/joinus",methods=['GET','POST'])</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">()</span>:</span></span><br><span class="line">    data=request.get_json(force=<span class="keyword">True</span>)</span><br><span class="line">    <span class="keyword">if</span> data:</span><br><span class="line">        print(data)</span><br><span class="line">        <span class="keyword">return</span> jsonify(&#123;<span class="string">"status"</span>: <span class="keyword">True</span>&#125;)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> jsonify(&#123;<span class="string">"status"</span>: <span class="keyword">False</span>&#125;)</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(&#123;</span><br><span class="line">	type:<span class="string">'POST'</span>,</span><br><span class="line">	crossDomain: <span class="literal">true</span>,</span><br><span class="line">	url: <span class="string">"http://127.0.0.1:5000/joinus"</span>,</span><br><span class="line">	data: <span class="built_in">JSON</span>.stringify(data),</span><br><span class="line">	dataType : <span class="string">'json'</span>,</span><br><span class="line">	success:<span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</span><br><span class="line">		alert(<span class="string">"提交成功"</span>);</span><br><span class="line">	&#125;,</span><br><span class="line">	error: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>)</span>&#123;</span><br><span class="line">		<span class="keyword">var</span> json_data=<span class="built_in">JSON</span>.stringify(res);</span><br><span class="line">		alert(json_data);</span><br><span class="line">		<span class="comment">// alert("现在不迎新哦~");</span></span><br><span class="line">	&#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>感觉第三种方便点,第二种也不错</p>
</blockquote>

      
    </div>

    
      
      



      
      
    

    
      <footer class="post-footer">
        
          <div class="post-tags">
            
              <a href="/tags/开发/">开发</a>
            
              <a href="/tags/flask/">flask</a>
            
              <a href="/tags/ajax/">ajax</a>
            
          </div>
        
        
        
  <nav class="post-nav">
    
      <a class="prev" href="/2018/02/01/Django自带认证系统邮件模板自定义/">
        <i class="iconfont icon-left"></i>
        <span class="prev-text nav-default">Django自带认证系统邮件模板自定义</span>
        <span class="prev-text nav-mobile">上一篇</span>
      </a>
    
    
      <a class="next" href="/2018/01/14/一道XXE和SSRF的题目/">
        <span class="next-text nav-default">一道XXE漏洞和SSRF结合的题目</span>
        <span class="prev-text nav-mobile">下一篇</span>
        <i class="iconfont icon-right"></i>
      </a>
    
  </nav>

      </footer>
    

  </article>


          </div>
          
  <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div> 
    </div>
  </div>


        </div>
      </main>

      <footer id="footer" class="footer">

  <div class="social-links">
    
      
        
          <a href="https://github.com/bay1" class="iconfont icon-github" title="github"></a>
        
      
    
      
        
          <a href="http://weibo.com/3190704711/profile?topnav=1&wvr=6&is_all=1" class="iconfont icon-weibo" title="weibo"></a>
        
      
    
      
    
      
    
      
    
    
    
  </div>


<div class="copyright">
  <span class="copyright-year">
    
    &copy; 
     
      2016 - 
    
    2018
    <span class="author">bay1</span>
  </span>
</div>
      </footer>

      <div class="back-to-top" id="back-to-top">
        <i class="iconfont icon-up"></i>
      </div>
    </div>

    
  
  <script type="text/javascript">
    var disqus_config = function () {
        this.page.url = 'https://bay1.top/2018/01/31/Ajax与Flask传值的跨域问题/';
        this.page.identifier = '2018/01/31/Ajax与Flask传值的跨域问题/';
        this.page.title = 'Ajax与Flask传值的跨域问题';
    };
    (function() {
    var d = document, s = d.createElement('script');

    s.src = '//https-blog-flywinky-top-1.disqus.com/embed.js';

    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
    })();  
  </script>



    
  





  
    <script type="text/javascript" src="/lib/jquery/jquery-3.1.1.min.js"></script>
  

  
    <script type="text/javascript" src="/lib/slideout/slideout.js"></script>
  

  
    <script type="text/javascript" src="/lib/fancybox/jquery.fancybox.pack.js"></script>
  


    <script type="text/javascript" src="/js/src/even.js?v=2.6.0"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=2.6.0"></script>
<script src="/js/prettify.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $('pre').addClass('prettyprint');
   prettyPrint();
 })
</script>
  </body>
</html>
